#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <memory>
#include <functional>

#include "Log.hpp"
#include "InerAddr.hpp"
#include "Socket.hpp"

using namespace std;
using namespace socket_ns;
class TcpServer;

// void Service(sock_sptr sockfd, InetAddr client)
using io_service_t =function<void(sock_sptr sockfd, InetAddr client)>;
class ThreadData
{
public:
    ThreadData(sock_sptr fd, InetAddr client, TcpServer *s) : sockfd(fd), clientaddr(client), self(s)
    {
    }
    ~ThreadData()
    {
    }

public:
    sock_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};
class TcpServer
{
public:
    TcpServer(int port,io_service_t service)
        //InetAddr(const string &ip,uint16_t port)
        :_localaddr("0",port)
        ,_listensock(std::make_unique<TcpSocket>())
        ,_isrunning(false)
        ,_service(service)
    {
        _listensock->BuildListenSocket(_localaddr);
    }
    
    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->_service(td->sockfd, td->clientaddr);
        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        // 4.不能直接接受数据，要先获取连接
        while (_isrunning)
        {   
            InetAddr peeraddr;
            sock_sptr normalsock=_listensock->Accepter(&peeraddr);

            pthread_t t;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this);
            pthread_create(&t, nullptr, HandlerSock, td); // 将线程设置为分离状态
        }
    }
    ~TcpServer()
    {
    }

private:
    InetAddr _localaddr;
    unique_ptr<Socket> _listensock;
    bool _isrunning;

    io_service_t _service;
};